import { getDomain, buildQueryString } from '../utils/tools';

class Axios {
  private timeout: number;
  private withCredentials: boolean;

  constructor(timeout: number = 0, withCredentials: boolean = false) {
    this.timeout = timeout;
    this.withCredentials = withCredentials;
  }
  private dynamicDomain(originUrl: string): Promise<string> {
    return new Promise((resolve) => {
      const originHost = getDomain(location.protocol + originUrl);
      const host = getDomain();
      resolve(originUrl.replace(originHost, host));
    });
  }

  public get(originUrl: string, options: { params: any; withCredentials?: boolean }): Promise<any> {
    return this.dynamicDomain(originUrl).then((url) => {
      const xhr = new XMLHttpRequest();
      const queryString = buildQueryString(options.params);
      const requestUrl = queryString ? `${url}?${queryString}` : url;
      return new Promise<any>((resolve, reject) => {
        xhr.open('GET', requestUrl, true);
        if (this.timeout > 0) {
          xhr.timeout = this.timeout;
        }
        // 带cookie如果为空，则使用初始化默认时的内容
        const withCredentials =
          options.withCredentials !== void 0 ? options.withCredentials : this.withCredentials;
        xhr.withCredentials = withCredentials;
        xhr.onload = function () {
          if (this.status === 200) {
            resolve(JSON.parse(this.responseText));
          } else {
            reject(new Error('Request failed: ' + this.status));
          }
        };
        xhr.ontimeout = function () {
          reject(new Error('Request timeout'));
        };
        xhr.onerror = function () {
          reject(new Error('Request failed'));
        };
        xhr.send();
      });
    });
  }

  public post(
    originUrl: string,
    options: { data: object; withCredentials?: boolean }
  ): Promise<any> {
    return this.dynamicDomain(originUrl).then((url) => {
      const xhr = new XMLHttpRequest();
      return new Promise<any>((resolve, reject) => {
        xhr.open('POST', url, true);
        if (this.timeout > 0) {
          xhr.timeout = this.timeout;
        }
        // 带cookie如果为空，则使用初始化默认时的内容
        const withCredentials =
          options.withCredentials !== void 0 ? options.withCredentials : this.withCredentials;
        xhr.withCredentials = withCredentials;
        xhr.withCredentials = this.withCredentials;
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.onload = function () {
          if (this.status === 200) {
            resolve(JSON.parse(this.responseText));
          } else {
            reject(new Error('Request failed: ' + this.status));
          }
        };
        xhr.ontimeout = function () {
          reject(new Error('Request timeout'));
        };
        xhr.onerror = function () {
          reject(new Error('Request failed'));
        };
        xhr.send(JSON.stringify(options.data));
      });
    });
  }
}
export default Axios;
